package com.atguigu.registration.msm.controller;

import com.atguigu.registration.common.result.Result;
import com.atguigu.registration.msm.service.MsmService;
import com.atguigu.registration.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Jiang Yizhi
 * @Date: 2022/5/4 7:26 AM
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /** 发送手机验证码 */
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        /** 先看redis里面有没有 */
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        /** 如果从redis拿不到，生成验证码 */
        code = RandomUtil.getSixBitRandom();
        redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
        return Result.ok();
//        /** 调用service方法，通过整合短信服务进行发送 */
//        boolean isSent = msmService.send(phone, code);
//        /** 生成的验证码放到redis里面，设置有效时间 */
//        if (isSent) {
//            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
//            return Result.ok();
//        } else {
//            return Result.fail();
//        }
    }
}
